#!/usr/bin/env bash

set -eu
set -o pipefail

get_pr() {
    local -r pr_number="$1"

    curl -H "Authorization: token $GITHUB_API_TOKEN" \
        "https://api.github.com/repos/$PROJECT_SLUG/pulls/$pr_number"
}

get_pr_meta() {
    cat - | jq -r '.head | .repo.full_name, .ref'
}

sync() {
    local -r remote_name="$1"
    local full_name= ref=

    read full_name
    read ref

    git remote add "$remote_name" "git@github.com:$full_name.git" || :
    git fetch "$remote_name" "$ref"
    git checkout -b "${remote_name}_${ref}" "$remote_name/$ref"
}

sync_forked_pr() {
    local -r pr_number="$1"

    get_pr "$pr_number" | get_pr_meta | sync "pr_$pr_number"
}

sync_forked_pr "$1"